import { ref } from 'vue'
import { supabase } from '../../lib/supabase'

// 图片压缩配置
interface CompressionOptions {
  maxSizeMB: number
  maxWidthOrHeight: number
  useWebWorker: boolean
  fileType?: string
}

export const useMovieFileUpload = () => {
  // 上传状态
  const isUploading = ref(false)
  const uploadProgress = ref(0)
  const uploadError = ref<string | null>(null)

  // 允许的图片类型与大小（前端支持10MB，压缩后目标2MB以下）
  const MAX_IMAGE_BYTES = 10 * 1024 * 1024 // 10MB
  const ALLOWED_IMAGE_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])

  // 默认压缩配置
  const DEFAULT_COMPRESSION_OPTIONS: CompressionOptions = {
    maxSizeMB: 1.8, // 压缩后最大1.8MB，留出余量
    maxWidthOrHeight: 1920, // 最大宽度或高度1920px
    useWebWorker: true,
    fileType: 'image/jpeg' // 统一转换为JPEG格式
  }

  // 图片压缩函数
  const compressImage = async (file: File, options: Partial<CompressionOptions> = {}): Promise<File> => {
    try {
      // 动态导入压缩库，避免打包时包含
      const imageCompression = await import('browser-image-compression')
      
      const compressionOptions = {
        ...DEFAULT_COMPRESSION_OPTIONS,
        ...options
      }

      // 如果文件小于2MB且尺寸合理，跳过压缩
      if (file.size <= 2 * 1024 * 1024) {
        const img = new Image()
        
        return new Promise((resolve, reject) => {
          img.onload = () => {
            if (img.width <= 1920 && img.height <= 1920) {
              resolve(file) // 无需压缩
            } else {
              // 尺寸过大，需要压缩
              imageCompression.default(file, compressionOptions)
                .then(resolve)
                .catch(reject)
            }
          }
          img.onerror = reject
          img.src = URL.createObjectURL(file)
        })
      }

      // 文件大于2MB，需要压缩
      console.log(`开始压缩图片: ${formatFileSize(file.size)} -> 目标: 2MB以下`)
      
      // 执行压缩
      const compressedFile = await imageCompression.default(file, compressionOptions)
      
      // 验证压缩结果
      if (compressedFile.size > 2 * 1024 * 1024) {
        console.warn(`压缩后仍超过2MB (${formatFileSize(compressedFile.size)})，尝试更激进的压缩`)
        
        // 尝试更激进的压缩设置
        const aggressiveOptions = {
          ...compressionOptions,
          maxSizeMB: 1.5, // 降低到1.5MB
          maxWidthOrHeight: 1600 // 降低尺寸限制
        }
        
        const aggressiveCompressed = await imageCompression.default(file, aggressiveOptions)
        console.log(`激进压缩后: ${formatFileSize(aggressiveCompressed.size)}`)
        return aggressiveCompressed
      }
      
      console.log(`压缩成功: ${formatFileSize(file.size)} -> ${formatFileSize(compressedFile.size)}`)
      return compressedFile
    } catch (error) {
      console.warn('图片压缩失败，使用原文件:', error)
      return file // 压缩失败时返回原文件
    }
  }

  // 验证图片文件
  const validateImageFile = (file: File): void => {
    if (!ALLOWED_IMAGE_MIME_TYPES.has(file.type)) {
      throw new Error('仅支持 JPG/PNG/WebP 图片格式')
    }
    
    if (file.size > MAX_IMAGE_BYTES) {
      throw new Error(`图片大小不能超过 ${formatFileSize(MAX_IMAGE_BYTES)}`)
    }
  }

  // 上传封面图片到Supabase Storage
  const uploadCoverImage = async (
    coverFile: File | null, 
    originalCoverUrl?: string,
    compressedFile?: File | null // 新增：已压缩的文件
  ): Promise<string | undefined> => {
    // 如果没有新文件且没有预览，说明用户删除了封面
    if (!coverFile && !originalCoverUrl) {
      return ''  // 返回空字符串来清空封面
    }
    
    // 如果没有新文件但有预览，返回原URL
    if (!coverFile) {
      return originalCoverUrl
    }

    try {
      // 基础校验
      validateImageFile(coverFile)
      
      // 优先使用已压缩的文件，如果没有则进行压缩
      let fileToUpload: File
      if (compressedFile) {
        console.log('使用已压缩的文件，跳过重复压缩')
        fileToUpload = compressedFile
      } else {
        console.log('开始压缩图片...')
        fileToUpload = await compressImage(coverFile)
      }
      
      // 生成文件名
      const fileExt = 'jpg' // 统一使用jpg格式
      const fileName = `${Date.now()}-${Math.random().toString(36).substring(2)}.${fileExt}`
      const filePath = `movie-covers/${fileName}`

      // 更新上传状态
      isUploading.value = true
      uploadProgress.value = 0

      // 上传到Supabase Storage
      const { error } = await supabase.storage
        .from('movies')
        .upload(filePath, fileToUpload, {
          cacheControl: '3600',
          upsert: false,
          contentType: 'image/jpeg',
        })

      if (error) {
        throw new Error(`上传封面失败: ${error.message}`)
      }

      // 获取公共URL
      const { data: urlData } = supabase.storage
        .from('movies')
        .getPublicUrl(filePath)

      uploadProgress.value = 100
      return urlData.publicUrl
      
    } catch (error) {
      uploadError.value = error instanceof Error ? error.message : '上传失败'
      throw error
    } finally {
      isUploading.value = false
    }
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 重置上传状态
  const resetUploadState = () => {
    uploadProgress.value = 0
    uploadError.value = null
  }

  // 获取压缩后的文件信息（用于预览）
  const getCompressedFileInfo = async (file: File): Promise<{ file: File, size: string, dimensions?: { width: number, height: number } }> => {
    try {
      const compressedFile = await compressImage(file)
      const size = formatFileSize(compressedFile.size)
      
      // 获取图片尺寸
      const dimensions = await new Promise<{ width: number, height: number }>((resolve) => {
        const img = new Image()
        img.onload = () => {
          resolve({ width: img.width, height: img.height })
        }
        img.src = URL.createObjectURL(compressedFile)
      })
      
      return { file: compressedFile, size, dimensions }
    } catch (error) {
      console.warn('获取压缩文件信息失败:', error)
      return { file, size: formatFileSize(file.size) }
    }
  }

  return {
    // 状态
    isUploading,
    uploadProgress,
    uploadError,
    
    // 方法
    uploadCoverImage,
    compressImage,
    validateImageFile,
    getCompressedFileInfo,
    formatFileSize,
    resetUploadState,
    
    // 常量
    MAX_IMAGE_BYTES,
    ALLOWED_IMAGE_MIME_TYPES
  }
}
